<template>
    <div style="width:90%;">
        <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px">
            <el-button @click="goback()" size="mini" type="primary" style="margin-left:1000px">返回</el-button>
            <el-input v-model="planForm.uuid" type="hidden"></el-input>
            <el-input v-model="planForm.orgSeq" type="hidden"></el-input>
           
            <el-form-item label="品鉴酒名称：" prop="name" >
                <el-input
                    v-model="planForm.name"
                    :disabled="disabledFlag"
                    style="width:300px;"
                    placeholder="请输入品鉴酒名称"
               
                    show-word-limit
                ></el-input>
            </el-form-item>

                 <el-form-item label="规格：" prop="spec" >
                <el-input
                    v-model="planForm.spec"
                    :disabled="disabledFlag"
                    style="width:300px;"
                    placeholder="请输入品鉴酒规格"
            
                    show-word-limit
                ></el-input>
                <span>ml/瓶</span>
            </el-form-item>
               <el-form-item label="兑换所需酒红包额度:" prop="packetQuotaMace" label-width="150px">
                <el-input
                    v-model="planForm.packetQuotaMace"
                    :disabled="disabledFlag"
                    style="width:100px;"
                    placeholder=""
              
                    show-word-limit
                ></el-input>
                <span>ml</span>
              
            </el-form-item>
                  <el-form-item label="每人每月兑换上限:" prop="upLimit" >
                <el-input
                    v-model="planForm.upLimit"
                    :disabled="disabledFlag"
                    style="width:100px;"
                    placeholder=""
              
                    show-word-limit
                ></el-input>
                <span>瓶</span>
            
            </el-form-item>
                   <el-form-item label="排序:" prop="sortNo" >
                <el-input
                    v-model="planForm.sortNo"
                    :disabled="disabledFlag"
                    style="width:100px;"
                    placeholder=""
              
                    show-word-limit
                ></el-input>
          
            
            </el-form-item>
    
 <el-form-item label="状态" prop="status">
                <el-select v-model="planForm.status" :disabled="disabledFlag">
                    <el-option
                        v-for="item in typeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="品鉴酒图片:" prop="imgListone">
                <image-upload v-model="planForm.imgListone" :size="'400x400'" :limit="1"></image-upload>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm('planForm')" v-if="!disabledFlag">保 存</el-button>
                <el-button @click="resetForm('planForm')">取 消</el-button>
            </el-form-item>
        </el-form>

        <el-dialog title="选择优惠券" :visible.sync="dialogVisibleCoupon" width="55%">
            <el-form
                :inline="true"
                :model="formCoupon"
                class="search-form-inline"
                style="margin-top:-20px;"
            >
                <el-input v-model="formCoupon.couponName" style="width:200px;" placeholder="优惠券名称"></el-input>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="getCouponList()"
                >查询</el-button>
            </el-form>
            <el-table
                ref="singleTable"
                :data="couponList"
                @selection-change="couponChecked"
                border
                style="font-size: 10px;width:100%;"
                height="300"
                :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column
                    prop="couponName"
                    label="优惠券名称"
                    width="200"
                    header-align="center"
                
                ></el-table-column>
                <el-table-column prop="couponSeq" label="优惠券编号" width="150" header-align="center"></el-table-column>
                <el-table-column prop="couponMoney" label="优惠券面值" width="150" header-align="center">
                    <template slot-scope="scope">
                        <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
                    </template>
                </el-table-column>
                <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleCoupon = false">取 消</el-button>
                <el-button
                    type="primary"
                    @click="couponConfirm()"
                    :disabled="this.lsCouponList.length!=1"
                >确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// import {
//     addPrize,
//     updatePrize,
//     queryGenCoupon
// } from "@/api/prizeLibrary";


import {
    addPrize,
    updatePrize,
    queryGenCoupon
} from "@/api/tastingWineManage";
import {
  queryPromotionList,
  queryPromotionById,
  queryCouponById,
  savePromotion,
  updatePromotionStatus,
  createTPlan
} from "@/api/promotionProgramEdit";
import imageUpload from "@/page/common/Image-upload";
import { queryCouponList } from "@/api/promotionProgramEdit";

export default {
  data() {
    return {
      keepAlive:true,
      logininfo: {},
      orgList: [],
      orgSeq: "",
      loading: true,
      typeOptions: [
              {value: "0",label: '停用'}, 
              {value: "1",label: '启用'}],
      lsPlanCouponList: [],
      lsCouponList: [],
      planCouponList: [],
      couponList: [],
      planForm: {
        uuid: "",
 
        name: "",
        spec: "",
        packetQuotaMace:"",
        sortNo:"",
        upLimit: "",
     
        status: "",
 
        imgListone: [],
        tastPic: "",
    
      },
      formCoupon: {
        couponName: ""
      },
      dialogVisibleCoupon: false,
      disabledFlag: false,
      listQuery: {
        current: 1,
        size: 10
      },
      total: 0,
      planRules: {
    
        name: [{ required: true, message: "请输入品鉴酒名称", trigger: "blur" }],
        spec: [{ required: true, message: "请输入规格", trigger: "blur" }],
        packetQuotaMace: [{ required: true, message: "请输入兑换所需酒红包额度", trigger: "blur" }],
         upLimit: [{ required: true, message: "请输入每人每月兑换上限", trigger: "blur" }],
        sortNo: [{ required: true, message: "请输入排序", trigger: "blur" }],
             status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        imgListone: [{ required: true, message: "请上传品鉴酒图片", trigger: "blur" }],
     
      }
    };
  },
  components: {
        imageUpload
    },
  mounted() {
    this.logininfo = localStorage.getItem("logininfo");
    this.orgList = JSON.parse(this.logininfo).orgList;
    this.orgSeq = this.orgList[0].orgSeq;
    this.planForm.orgSeq = this.orgList[0].orgSeq;
this.disabledFlag=this.$route.params.disabledFlag
    var v = this.$route.params.edit;
    if (v) {
      // 修改，回显值
      this.planForm.uuid = v.uuid;
      this.planForm.name = v.name;
      // this.planForm.prizeType = String(v.prizeType);
      this.planForm.tastPic = v.tastPic;
      this.planForm.couponId = v.couponId;
      // this.planCouponList = res.result.promotionCouponInfo;
      this.planForm.imgListone = v.tastPic == null || v.tastPic == ""?[]:[v.tastPic];
      this.planForm.spec = v.spec;
      this.planForm.upLimit = v.upLimit;
      this.planForm.endTime = v.endTime;
      this.planForm.status = v.status;
   this.planForm.packetQuotaMace = v.packetQuotaMace;
  this.planForm.sortNo = v.sortNo;
      this.queryPromotionById(v.couponId);
    } else {
      // 新增，默认值
      this.planForm.uuid = "";
      this.planForm.status = "1";
      this.getCouponList();
    }
  },
  methods: {
    goback() {
      this.$router.go("-1");
    },
    quantityBlur(e, idx) {
      if (e.target.value == '') { return; }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: "限领数量请输入正整数",
          type: "warning"
        });
        e.target.value = '';
      }
    },
    numberBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    queryPromotionById(uuid) {
      let data = {
        size: 100,
        current: 1,
        condition: {
        },
        ascs: [],
        descs: []
      };
      queryGenCoupon(data).then(res => {
        if (
          res.records != null &&
          res.records.length > 0
        ) {
          // this.planCouponList =res.records;
          // 去掉已选的
        for (var i in res.records) {
          console.log(uuid);
          console.log(res.records[i]);
          if(uuid == res.records[i].uuid){
          this.planCouponList.push(res.records[i]);
          }
        }
          
        }
        this.getCouponList();
      });
      this.loading = false;
    },

    getCouponList() {
      let data = {
        size: 100,
        current: 1,
        condition: {
          status: 1,
          couponType: 1,
          keyWord: this.formCoupon.couponName
        },
        ascs: [],
        descs: []
      };
      queryGenCoupon(data).then(res => {
        this.couponList = res.records;
        // 去掉已选的
        for (var i in this.planCouponList) {
          this.removeByValue(
            this.couponList,
            "uuid",
            this.planCouponList[i].uuid
          );
        }
      });
      this.loading = false;
    },

    planCouponChecked(row) {
      this.lsPlanCouponList = row;
    },
    couponChecked(row) {
      this.lsCouponList = row;
      if (this.lsCouponList.length > 1) {
          this.$refs.singleTable.toggleRowSelection(this.lsCouponList[0]);
          }
    },
    selectCoupon() {
      // 显示选择卡券对话框
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
    },
    deleteCoupon() {
      // 删除已选择的卡券
      this.couponList = this.couponList.concat(this.lsPlanCouponList);
      for (var i in this.lsPlanCouponList) {
        this.removeByValue(
          this.planCouponList,
          "uuid",
          this.lsPlanCouponList[i].uuid
        );
      }
    },
    couponConfirm() {
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      this.planCouponList = this.lsCouponList;//this.planCouponList.concat(this.lsCouponList);
      // for (var i in this.lsCouponList) {
      //   this.removeByValue(this.couponList, "uuid", this.lsCouponList[i].uuid);
      // }
    },

    submitForm(formName) {
      // 保存奖品
      // if (this.planForm.prizeType == "2"){
      // if (this.planForm.name == "" || this.planForm.name == null) {
      //   this.$message.error("请输入奖品名称");
      //   return;
      // }
      // }
      // if (this.planForm.imgListone.length == 0) {
      //   this.$message.error("请上传图片");
      //   return;
      // }
      // if (this.planForm.prizeType=="1" && this.planCouponList.length != 1) {
      //   this.$message.error("请选择1张卡券,多余的请删除");
      //   return;
      // }
      // for (var i in this.planCouponList) { 
      //   // 删除提交时不需要的属性或容易导致错误的属性
      //   if (
      //     this.planCouponList[i].couponId != null &&
      //     this.planCouponList[i].couponId != undefined
      //   ) {
      //     this.planCouponList[i].couponId = this.planCouponList[i].uuid;
      //   }
      //   delete this.planCouponList[i].createTime;
      //   delete this.planCouponList[i].createUser;
      //   delete this.planCouponList[i].updateTime;
      //   delete this.planCouponList[i].updateUser;
      //   delete this.planCouponList[i].beginTime;
      //   delete this.planCouponList[i].endTime;
      //   delete this.planCouponList[i].comments;
      //   delete this.planCouponList[i].validCreateDate;
      //   delete this.planCouponList[i].validEndDate;
      // }
      // this.planForm.promotionCouponInfo = this.planCouponList;
      // if (this.planForm.prizeType=="1"){
      // this.planForm.couponId = this.planForm.promotionCouponInfo[0].uuid;
      // this.planForm.name = this.planForm.promotionCouponInfo[0].couponName;
      // }
          if (this.planForm.name == "" || this.planForm.name == null) {
        this.$message.error("请输入品鉴酒名称");
        return;
      }
         if (this.planForm.spec == "" || this.planForm.spec == null) {
        this.$message.error("请输入品鉴酒规格");
        return;
      }
       if (this.planForm.packetQuotaMace == "" || this.planForm.packetQuotaMace == null) {
        this.$message.error("请输入兑换所需酒红包额度");
        return;
      }
        if (this.planForm.upLimit == "" || this.planForm.upLimit == null) {
        this.$message.error("请输入每人每月兑换上限");
        return;
      }
        if (this.planForm.sortNo == "" || this.planForm.sortNo == null) {
        this.$message.error("请输入排序");
        return;
      }
       if (this.planForm.imgListone.length == 0) {
        this.$message.error("请上传品鉴酒图片");
        return;
      }
      this.planForm.tastPic = this.planForm.imgListone[0]
      
      
      // console.log(this.planForm);
      this.keepAlive = false;
      if(this.planForm.uuid == ""){
      addPrize(this.planForm).then(res => {
        if (res.code == "1") {
          this.$message({
            showClose: true,
            message: "保存成功",
            type: "success"
          });
          this.$router.push("tastingWineManage");
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error"
          });
        }
      });
      } else {
        updatePrize(this.planForm).then(res => {
        if (res.code == "1") {
          this.$message({
            showClose: true,
            message: "修改成功",
            type: "success"
          });
          this.$router.push("tastingWineManage");
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error"
          });
        }
      });
      }
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    handleRemove(file, fileList) {
      let newfileList = [];
      fileList.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url
        };
        newfileList.push(data);
      });
      this.fileList = newfileList;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push("tastingWineManage");
    },
       beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    to.meta.keepAlive = this.keepAlive; // C 跳转到 A 时让 A 不缓存，即刷新
    next();
  },
  }
};
</script>
<style lang="less" scoped>
.el-col-20 {
    border: 1px solid #ebeef5;
    margin-left: 150px;
    width: 60%;
}
.el-input {
    width: 60%;
}
.search-form-inline {
    border: 1px solid #ebeef5;
    line-height: 30px;
    padding: 12px;
    margin-bottom: 5px;
}
thead {
    .el-table-column--selection {
        .cell {
            display: none;
        }
    }
}
</style>